<template>
  <a-card class="general-card" title="直播商品" :bordered="false">
    <a-row style="margin-bottom: 16px">
      <a-tabs
          v-model="type"
          :default-active-key="params.auditStatus"
          auto-switch
          @change="tabClick"
          class="tabs"
      >
        <a-tab-pane
            v-for="(item, index) in liveTabWay"
            :key="index"
            :title="item.title"
            :name="item.key + ''"
        ></a-tab-pane>
      </a-tabs>
    </a-row>
    <searchTable
      :columns="columnsSearch"
      time-type="timestamp"
      @reset="
        (val) => {
          apiParamsTable = { ...apiParamsTable, ...val };
        }
      "
      @search="
        (val) => {
          apiParamsTable = { ...apiParamsTable, ...val };
        }
      "
    >
    </searchTable>
    <a-alert v-if="true" style="margin-bottom: 16px">
      由于直播商品需经过小程序直播平台的审核，你需要在此先提审商品，为了不影响直播间选取商品，请提前1天提审商品；
    </a-alert>

    <a-row style="margin-bottom: 16px">
      <a-col :span="16">
        <a-space>
          <a-button type="outline" @click="addNewLiveGoods">
            选择商品
          </a-button>
          <a-button v-if="params.auditStatus == '0'"> 更新状态 </a-button>
        </a-space>
      </a-col>
    </a-row>
    <tablePage
      ref="tablePageRef"
      :columns="columnsTable"
      :methods="sortMethods"
      :data-list="isSelectData?liveGoodsData:null"
      :api-params="apiParamsTable"
      :api="isSelectData?null:getLiveGoods"
      :bordered="true"
    >
      <!-- <template #goods="{data}">
      <div class="flex">
        <a-image width="50" height="50" :src="data.goodsImage" show-loader></a-image>
        <div  style="margin-left: 5px">{{ data.name }}</div>
      </div>
    </template> -->
      <template #price="{ data, rowIndex }">
        <div v-if="params.auditStatus == '99'">
          <a-radio-group
            v-model="data.priceType"
            @change="changeRadio($event, rowIndex)"
          >
            <div>
              <a-radio :value="1">一口价:</a-radio>
              <a-input-number
                v-if="liveGoodsData[rowIndex].priceType == 1"
                v-model="liveGoodsData[rowIndex].price"
                :min="0.1"
                style="width: 100px"
              />
            </div>
            <div>
              <a-radio :value="2">区间价:</a-radio>
              <span v-if="liveGoodsData[rowIndex].priceType == 2">
                <a-input-number
                  v-model="liveGoodsData[rowIndex].price"
                  :min="0.1"
                  style="width: 100px"
                />至
                <a-input-number
                  v-model="liveGoodsData[rowIndex].price2"
                  :min="0.1"
                  style="width: 100px"
                />
              </span>
            </div>
            <div>
              <div>
                <a-radio :value="3">折扣价:</a-radio>
                <span v-if="liveGoodsData[rowIndex].priceType == 3">
                  原价
                  <a-input-number
                    v-model="liveGoodsData[rowIndex].price"
                    :min="0.1"
                    style="width: 100px"
                  />
                  现价
                  <a-input-number
                    v-model="liveGoodsData[rowIndex].price2"
                    :min="0.1"
                    style="width: 100px"
                  />
                </span>
              </div>
            </div>
          </a-radio-group>
        </div>
        <div v-else>
          <span v-if="data.priceType == 1">{{
            unitPrice(data.price, '¥')
          }}</span>
          <span v-if="data.priceType == 2"
            >{{ unitPrice(data.price, '¥') }}至{{
              unitPrice(data.price2, '¥')
            }}</span
          >
          <span v-if="data.priceType == 3"
            >{{ unitPrice(data.price2, '¥')
            }}<span class="original-price">{{
              unitPrice(data.price, '¥')
            }}</span></span
          >
        </div>
      </template>
      <template #delete="{ data }"
        ><a-button type="text" status="danger" @click="deleteDetail(data)"
          >删除</a-button
        ></template
      >
      <template v-if="selectedMember" #detail="{ data }"
        ><a-button type="text" status="success" @click="changDetail(data)"
          >查看</a-button
        ></template
      >
      <template v-else #change="{ data }"
        ><a-button type="text" @click="changUserList(data)"
          >选择</a-button
        ></template
      >
      <!--<template #detail="{ data }" v-if="selectedMember"><a-button @click="changDetail(data)" type="text" status="success">查看</a-button></template>-->
      <!--<template #change="{data}" v-else><a-button @click="changUserList(data)"  type="text">选择</a-button></template>-->
    </tablePage>
    <div v-if="params.auditStatus == '99'" class="submit">
      <a-button type="primary" @click="saveLiveGoods">保存商品</a-button>
    </div>

    <skuselect
      ref="skuSelect"
      :goods-or-sku="true"
      :api-params="apiParams"
      :default-goods-selected-list="liveGoodsData"
      @change="changSkuList"
    ></skuselect>
  </a-card>
</template>

<script setup lang="ts">
  import searchTable from '@/components/search-column/index.vue';
  import tablePage from '@/components/table-pages/index.vue';
  import { SearchRule, MethodsRule, ColumnsDataRule } from '@/types/global';
  import { getLiveGoods, addLiveStoreGoods } from '@/api/promotion';
  import { ref, watch, reactive, onMounted } from 'vue';
  import skuselect from '@/components/goods-sku-selector/index.vue';
  import { unitPrice } from '@/utils/filters';
  import { Message } from '@arco-design/web-vue';

  const apiParamsTable = ref({});
  const apiParams = ref({
    marketEnable: 'UPPER',
    authFlag: 'PASS',
  });
  const skuSelect = ref(null) as any; // 商品选择器
  const liveGoodsData = ref<Array<any>>([]);
  const isSelectData = ref<boolean>(false);
  const tablePageRef = ref('');
  const goodsSkuRef = ref('');
  const type = ref<string>('2');
  const emit = defineEmits<{ (e: 'callback', data: object): void }>();
  const liveTabWay = ref([
    { title: '待提审', key: 0 },
    { title: '已审核', key: 2 },
    { title: '审核中', key: 1 },
    { title: '审核未通过', key: 3 },
  ]) as any;
  const selectedMember = ref<boolean>(true); // 是否显示按钮
  const columnsSearch: Array<SearchRule> = [
    {
      label: '商品名称',
      model: 'goodsName',
      disabled: false,
      input: true,
    },
  ];

  const columnsTable: ColumnsDataRule[] = [
    {
      title: '商品',
      dataIndex: 'goods',
      width: 450,
      slot: true,
      slotData: {
        goods: {
          goodsImage: 'goodsImage',
          goodsName: 'name',
        },
      },
    },
    {
      title: '价格',
      dataIndex: 'price',
      width: 450,
      slot: true,
      slotTemplate: 'price',
    },

    {
      title: '库存',
      dataIndex: 'quantity',
      width: 100,
    },
  ];

  const sortMethods: MethodsRule = {
    title: '操作',
    // width: 150,
    methods: [
      {
        title: '删除',
        callback: 'delete',
        slot: true,
        slotTemplate: 'delete',
      },
      {
        title: '查看',
        callback: 'detail',
        slot: true,
        slotTemplate: 'detail',
      },
      {
        title: '选择',
        callback: 'change',
        slot: true,
        slotTemplate: 'change',
      },
    ],
  };
  const params = reactive<any>({
    auditStatus: type,
  });
  // 删除
  const deleteDetail = (val: any) => {
    console.log('删除', val);
  };
  // 查看详情
  const changDetail = (val: any) => {
    console.log(val);
  };
  // 清除新增的tab
  const clearNewLiveTab = () => {
    liveTabWay.value.forEach((item: any, index: number) => {
      return item.type == 99 && liveTabWay.value.splice(index, 1);
    });
  };
  const changeRadio = (event: any, index: number) => {
    liveGoodsData.value[index].priceType = event;
    isSelectData.value = true;
  };
  // 选择商品
  const addNewLiveGoods = () => {
    clearNewLiveTab();
    let arr = liveTabWay.value.filter(item => item.key === 99);
    if (!arr.length) {
      liveTabWay.value.push({
        key: 99,
        title: '新增商品',
      });
    }
    params.auditStatus = 99;
    skuSelect.value.modalData.visible = true;
  };

  const tabClick: any = (key: string) => {
    params.auditStatus = key;
    type.value = key;
  };
  // 选择的商品
  const changSkuList = (val: any) => {
    const list: any = [];
    val.forEach((e: any) => {
      const obj = {
        skuId: e.id,
        goodsId: e.goodsId,
        goodsImage: e.thumbnail || '',
        name: e.goodsName || '',
        quantity: e.quantity || '',
        storeName: e.storeName || '',
        price: e.price || '',
        price2: e.price2 || 0,
      };
      list.push(obj);
    });
    liveGoodsData.value = list;
    isSelectData.value = true;
  };
  const saveLiveGoods = async () => {
    const submits = liveGoodsData.value.map((element: any) => {
      return {
        goodsId: element.goodsId, // 商品id
        goodsImage: element.small, // 商品图片  最大为 300 * 300
        name: element.goodsName, // 商品昵称
        price: parseInt(element.price, 10), // 商品价格
        quantity: element.quantity, // 库存
        price2: element.price2 ? parseInt(element.price2, 10) : '', // 商品价格
        priceType: element.priceType, // priceType  Number  是  价格类型，1：一口价（只需要传入price，price2不传） 2：价格区间（price字段为左边界，price2字段为右边界，price和price2必传） 3：显示折扣价（price字段为原价，price2字段为现价， price和price2必传）
        skuId: element.id,
        url: `pages/product/goods?id=${element.id}&goodsId=${element.goodsId}`, // 小程序地址
      };
    });
    const res = await addLiveStoreGoods(submits);
    if (res.data.success) {
      Message.success('添加成功');
    }
    params.auditStatus = '0';
  };
  const init = async () => {
    const res = await getLiveGoods(params);
    if (res.data.success) {
      liveGoodsData.value = res.data.result.records;
      isSelectData.value = true;
    }
  };
  onMounted(async () => {
    init();
  });
  watch(type, (val) => {
    params.auditStatus = val;
    init();
  });
  const changUserList = (val: any) => {
    emit('callback', val);
  };
  defineExpose({
    selectedMember,
    sortMethods,
  });
</script>

<style lang="less" scoped>
  .original-price {
    margin-left: 10px;
    color: #999;
    text-decoration: line-through;
  }
  .submit {
    box-shadow: 3px 5px 12px rgba(0, 0, 0, 0.1);
    height: 60px;
    background: #fff;
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .tabs {
    width: 100%;
  }
</style>
